package com.hkd.user_api.controller;

import com.hkd.common.api.constants.AuthConstants;
import com.hkd.common.api.constants.CacheConstants;
import com.hkd.user_service.api.SysUserService;
import com.hkd.user_service.api.vo.BaseUserInfo;
import com.hkd.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author HKD
 * @date 2022/9/4 22:28
 */
public abstract class BaseController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysUserService sysUserService;

    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    protected String curUserId() {
        return getRequest().getHeader(AuthConstants.JWT_USER_Id);
    }

    protected BaseUserInfo curUser(){
        return curUser(false);
    }

    protected BaseUserInfo curUser(boolean refresh) {
        String userId = curUserId();
        BaseUserInfo baseUserInfo = redisUtil.get(CacheConstants.USER_TOKE + userId, BaseUserInfo.class);
        if (!refresh){
            return baseUserInfo;
        }else {
            BaseUserInfo baseUser = sysUserService.getUserById(userId).getData();
            redisUtil.set(CacheConstants.USER_TOKE+userId,baseUser);
            return baseUser;
        }
    }



}
